package sliver.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;

public abstract class FileUploadUtils {
	
	public static String rename(String oldName){
		
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		
		String ext = oldName.substring(oldName.lastIndexOf("."));
		String newName = "" + year + month + day + System.currentTimeMillis() + oldName.hashCode() + ext;
		
		return newName;
	}
	
	public static File moveToDisk(File image, String directory, String oldName){
		
		String newName = rename(oldName);
		
		File dest = new File(directory + newName);
		if(dest != null && !dest.exists()){
			boolean result = image.renameTo(dest);
			if(result == true)
				return dest;
		}
		
		return null;
	}
	
	public static void writeToDisk(File image, String newFile){
		
		FileInputStream reader = null;
		FileOutputStream writer = null;
		
		try {
			reader = new FileInputStream(image);
			writer = new FileOutputStream(newFile);
			
			byte[] buffer = new byte[1024];
			int len = reader.read(buffer);
			while(len != -1){
				writer.write(buffer, 0, len);
				
				len = reader.read(buffer);
			}
			
			writer.flush();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			
			try {
				if(reader != null)
					reader.close();
				
				if(writer != null)
					writer.close();
			} catch (Exception e) {
				e.printStackTrace();
			} finally{
				deleteFile(image.getPath());
			}
		}
	}
	
	public static void deleteFile(String filepath){
		
		File file = new File(filepath);
		
		if(file != null && file.exists())
			file.delete();
	}
}
